/*
 * jQuery File Upload Plugin JS Example 5.0.2
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://creativecommons.org/licenses/MIT/
 */

/*jslint nomen: true */
/*global $ */

$(function () {
    'use strict';
    // TODO: change the max file upload size to what is reasonable for your need
    var MAX_FILE_UPLOAD_SIZE = 500*1024;

    // fetch a batchid from the server and put it in the form data to be
    // uploaded with the images ($('#form-params').serialize() below
    jQuery.ajax({
      url: '/getbatchid',
      dataType: "json",
      success: function(data, textStatus, jqXHR) {
          try {
            $('#batchid').val(data.batchid);
          } catch(ex) {
            // debugger
          }
        }
    });
        
    $('#fileupload').fileupload({
        initUpload: function (event, files, index, xhr, handler, callBack) {
            if (files[index].size > 5000000) {
                /* Show 'FILE TOO BIG!' message to user ... */
                alert('file too big');
                return;
            }
            callBack();
        },
        errorMessageTimeoutId: 0,
        add: function (e, data) {
            var regexp = /\.(png)|(jpg)|(gif)$/i;
            var filestoobig = false;
            var fileswrongtype = false;

            var that = this;

            var removelist = [];
            // filter out invalid files
            jQuery.each(data.files, function(index,file) {
              if (file.fileSize > MAX_FILE_UPLOAD_SIZE) {
                filestoobig = true;
                removelist.push(index);
              } else if (!regexp.test(file.name)) {
                fileswrongtype = true;
                removelist.push(index);
              }
            });

            if (filestoobig || fileswrongtype) {
              // TODO: do some better ui here.
              $('#somefilesbad').show();
              if (this.errorMessageTimeoutId) {
                window.clearTimeout(this.errorMessageTimeoutId);
                this.errorMessageTimeoutId = 0;
              }
              this.errorMessageTimeoutId =
                  window.setTimeout(function() {
                    $('#somefilesbad').hide();
                    this.errorMessageTimeoutId=0;},3000, this);
            }

            // special case. we just removed every file added.
            if (removelist.length == data.files.length) {
              return;
            }

            // we want to remove out each element from file list that isn't ok
            if (removelist.length > 0) {
              removelist.reverse();
              jQuery.each(removelist, function(ii, indexToRemove) {
                data.files.splice(indexToRemove,1);
              });
            }


            // send extra params with request
            var uploadurlparams = $('#form-params').serialize();
            $.getJSON('getuploadurl?'+uploadurlparams, function (url) {
                data.url = url;
                $.blueimpUI.fileupload.prototype.options.add.call(that, e, data);
            });
        }
    });

    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload();

    // Load existing files:
    $.getJSON($('#fileupload form').prop('action'), function (files) {
        var fu = $('#fileupload').data('fileupload');
        fu._adjustMaxNumberOfFiles(-files.length);
        fu._renderDownload(files)
            .appendTo($('#fileupload .files'))
            .fadeIn(function () {
                // Fix for IE7 and lower:
                $(this).show();
            });
    });

    // Open download dialogs via iframes,
    // to prevent aborting current uploads:
    $('#fileupload .files a:not([target^=_blank])').live('click', function (e) {
        e.preventDefault();
        $('<iframe style="display:none;"></iframe>')
            .prop('src', this.href)
            .appendTo('body');
    });

});
